<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form label-width="80px" :inline="false">
        <el-form-item label="SPU名称">
          <el-input placeholder="SPU名称" v-model="SpuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select placeholder="请选择" v-model="(SpuInfo.tmId as number)">
            <el-option
              :label="trademark.tmName"
              :value="(trademark.id as number)"
              v-for="trademark in AllTrademarkList"
              :key="trademark.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
          <el-input
            placeholder="SPU描述"
            type="textarea"
            v-model="SpuInfo.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
          <el-upload
            v-model:file-list="fileList"
            :action="`${baseUrl}/admin/product/upload`"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
          >
            <el-icon><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-select placeholder="请选择销售属性" v-model="salesAttrInfo">
            <el-option
              :label="salesAttr.name"
              :value="`${salesAttr.id}:${salesAttr.name}`"
              v-for="salesAttr in seleteSalesAttrList"
              :key="salesAttr.id"
            >
            </el-option>
          </el-select>

          <el-button
            type="primary"
            size="default"
            @click="addSalesAttr"
            :disabled="!salesAttrInfo"
            >添加销售属性</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-table border stripe :data="SaleAttrList">
            <el-table-column type="index" width="70" label="序号" />
            <el-table-column label="属性名" prop="saleAttrName">
            </el-table-column>
            <el-table-column label="属性值列表">
              <template v-slot="{ row }">
                <div>
                  <!-- 展示销售属性值 -->
                  <el-tag
                    v-for="(item, index) in row.spuSaleAttrValueList"
                    :key="item.saleAttrValueName"
                    :type="`${index % 2 === 0 ? 'danger' : ''}`"
                    size="small"
                    :style="{ marginRight: '10px' }"
                    @close="deleTage(index, row.spuSaleAttrValueList)"
                    closable
                    >{{ item.saleAttrValueName }}</el-tag
                  >
                  <!-- input 输入销售属性添加 -->
                  <el-input
                    :autosize="{ minRows: 3, maxRows: 8 }"
                    v-if="row.isEdit"
                    placeholder="输入销售属性值"
                    size="small"
                    clearable
                    @blur="toLook(row)"
                    v-model="salesAttrInputValue"
                    ref="AddSalesAttrInputRef"
                  ></el-input>
                  <!-- 添加销售属性按钮 -->
                  <el-button
                    v-else
                    type="primary"
                    size="small"
                    @click="toEdit(row)"
                    icon="ele-Plus"
                    >添加销售属性值</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100"> </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="default" @click="saveSpu"
            >保存</el-button
          >
          <el-button size="default" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { cloneDeep } from "lodash";

export default defineComponent({
  name: "SpuInfo",
});
</script>

<script setup lang="ts">
import { reqGetAllTrademark, type ProductType } from "@/api/product";
import {
  reqGetAllSalesAttr,
  type salesAttrListType,
  type spuItemType,
  type spuSaleAttrItem,
  type spuSaleAttrList,
  type spuSaleAttrValueListType,
  reqAddSpuInfo,
  reqGetSalesAttrListBySpuId,
  reqGetImageListBySpuId,
  reqUpdataSpuInfo,
} from "@/api/spu";
import { ElMessage, type UploadUserFile } from "element-plus";
import { computed, onMounted, ref, nextTick } from "vue";
import useCategoryStore from "@/stores/category";

// 自定义事件
const emit = defineEmits<{
  (event: "cutSpuComponent", showIndex: number): void;
}>();

// 获取传入的props
const props = defineProps<{
  spuInfo: spuItemType;
}>();

// 当前开发环境的api地址
const baseUrl = import.meta.env.VITE_API_URL;

// categoryStore对象
const categoryStore = useCategoryStore();

// 照片墙数据
const fileList = ref<UploadUserFile[]>([]);

// 初始化请求数据
const AllTrademarkList = ref<ProductType>([]); //所有品牌数据
const AllSalesAttrList = ref<salesAttrListType>([]); //所有销售属性

// 请求所有品牌数据
const getAllTrademarkList = async () => {
  const result = await reqGetAllTrademark();
  AllTrademarkList.value = result;
};

// 请求所有销售属性数据
const getAllSalesList = async () => {
  const result = await reqGetAllSalesAttr();
  AllSalesAttrList.value = result;
};

// 初始化发送请求
onMounted(() => {
  getAllTrademarkList();
  getAllSalesList();

  if (SpuInfo.value.id) {
    getSalesAttrList();
    getImageList();
  }
});

// 新增时初始化数据 (回填数据)
const SpuInfo = ref<spuItemType>(cloneDeep(props.spuInfo));

// 根据spuId 获取销售属性列表及图片信息方法
const getSalesAttrList = async () => {
  const result = await reqGetSalesAttrListBySpuId(SpuInfo.value.id as number);
  console.log(result);
  // 销售属性数据回填
  SaleAttrList.value = result;
};

const getImageList = async () => {
  const result = await reqGetImageListBySpuId(SpuInfo.value.id as number);
  console.log(result);
  // 回填图片数据
  result.forEach((item) => {
    const imgObj = {
      name: "",
      url: "",
    };
    imgObj.name = item.imgName;
    imgObj.url = item.imgUrl;
    fileList.value.push(imgObj);
  });
};

// 图片上传成功时事件
const handleAvatarSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  // response 上传成功时响应数据
  // uploadFile 图片上传成功后的详细信息
  // uploadFiles 图片上传成功图片列表
  fileList.value = uploadFiles;
};

// 选中销售属性时的id与name
const salesAttrInfo = ref("");

// 销售属性列表数据
const SaleAttrList = ref<spuSaleAttrList>([]);

// 收集添加销售属性值中input框数据
const salesAttrInputValue = ref("");

// 添加销售属性框dom
const AddSalesAttrInputRef = ref();

// 点击添加销售属性按钮事件
const addSalesAttr = () => {
  // 获取销售属性值和id
  const [baseSaleAttrId, saleAttrName] = salesAttrInfo.value.split(":");
  // 添加数据
  SaleAttrList.value.push({
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: [],
    isEdit: false,
  });
  // 清空选项框数据
  salesAttrInfo.value = "";
};

// 计算出销售属性数据
const seleteSalesAttrList = computed(() => {
  // 遍历所有销售属性值列表
  return AllSalesAttrList.value.filter((salesAttr) => {
    // 判断所有销售属性列表中的值是否与展示销售属性值相同   相同则不收集返回false
    return !SaleAttrList.value.some((seleteSalesAttr) => {
      return seleteSalesAttr.saleAttrName === salesAttr.name;
    });
  });
});

// 点击添加属性值按钮事件
const toEdit = (row: spuSaleAttrItem) => {
  // 进入编辑模式
  row.isEdit = true;
  // 清空输入框数据
  salesAttrInputValue.value = "";
  nextTick(() => {
    // 获取焦点
    AddSalesAttrInputRef.value.focus();
  });
};

// 输入框失去焦点事件
const toLook = (row: spuSaleAttrItem) => {
  // 进入查看模式
  row.isEdit = false;

  // 非空验证
  if (!salesAttrInputValue.value)
    return ElMessage.error("销售属性值不能为空！");
  // 重复验证
  const isReUse = row.spuSaleAttrValueList.some(
    (item) => item.saleAttrValueName === salesAttrInputValue.value
  );
  if (isReUse) return ElMessage.error("销售属性值不能重复！");

  // 添加数据
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrName: row.saleAttrName,
    saleAttrValueName: salesAttrInputValue.value,
  });
};
// 点击展示销售属性关闭按钮事件
const deleTage = (index: number, list: spuSaleAttrValueListType) => {
  list.splice(index, 1);
};
// 点击保存 发送请求
const saveSpu = async () => {
  // 整理参数
  SpuInfo.value.spuImageList = [];
  SpuInfo.value.spuSaleAttrList = [];
  // 图片
  console.log(fileList.value);

  fileList.value.forEach((item) => {
    const obj = {
      imgName: "",
      imgUrl: "",
    };
    obj.imgName = item.name;
    obj.imgUrl = (item.response as any)?.data;
    SpuInfo.value.spuImageList?.push(obj);
  });

  // 销售属性
  SaleAttrList.value.forEach((item) => {
    SpuInfo.value.spuSaleAttrList?.push(item);
  });
  // console.log(SpuInfo.value);

  if (SpuInfo.value.id)
    // 修改请求
    await reqUpdataSpuInfo(SpuInfo.value);
  // 新增请求
  else await reqAddSpuInfo(SpuInfo.value);
  // 保存成功提示
  ElMessage.success("成功！");
  // 跳转到spuList页
  emit("cutSpuComponent", 1);
};
// 点击取消按钮 回到spuList页
const cancel = () => {
  emit("cutSpuComponent", 1);
};
</script>

<style scoped lang="scss"></style>
